﻿using System;
using System.Data.SqlClient;
using System.Web.UI;

namespace BwanaBank.BankOnline.WinUI.Window
{
    public partial class Register : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.Cookies["customer"] != null || Session["customer"] != null)
            {
                Response.Redirect("~/Customer/");
            }
            else if (Request.Cookies["admin"] != null || Session["admin"] != null)
            {
                Response.Redirect("~/Admin/");
            }
        }
        protected void Button_Register(object sender, EventArgs e)
        {
            var cn = new SqlConnection(@"Data Source=PAR-ROBHED-001\SQLEXPRESS;Initial Catalog=BWANABANK;Integrated Security=True");
            cn.Open();

            var firstName = UserName.Text;
            var lastName = Password.Text;
            var yearOfBirth = YearOfBirth.Text;
            var adress = Address.Text;
            var zipcode = Zipcode.Text;
            var country = Country.Text;
            var job = Metier.Text;
            var civility = RadioButton1.Checked == true ? "Monsieur" : "Madame";
            var email = Email.Text;
            var idAccount = RandomNumber(11111111, 99999999);
            //var password        = RandomNumber(55555555, 99999999);
            var statut = Int32.Parse(TypeContratList.SelectedItem.Value);

            var cmd = new SqlCommand("insert into [User] ([firstName], [lastName], [birthday], [address], [zipcode], [country], [civility], [email], [job], [idState], [idType], [idStatus]) " +
                                     "values ('" + firstName + "','" + lastName + "','" + yearOfBirth + "','" + adress + "','" + zipcode + "','" + country + "','" + civility + "','" + email + "','" + job + "','1','2','" + statut + "')", cn);
            cmd.ExecuteNonQuery();

            cmd = new SqlCommand("SELECT * FROM [User] WHERE firstName='" + UserName.Text + "' AND lastName='" + Password.Text + "'", cn);
            var dtr = cmd.ExecuteReader();
            if (dtr.Read())
            {
                var idUser = (int)dtr["idUser"];
                dtr.Dispose();
                dtr.Close();
                cmd = new SqlCommand("insert into [Account] ([idAccount], [idUser], [realBalance]) values ('" + idAccount + "','" + idUser + "','0')", cn);
                cmd.ExecuteNonQuery();
            }
            cn.Close();

            ScriptManager.RegisterClientScriptBlock(this, GetType(), "success", "alert('Votre demande a bien été prise en compte. Vous serez informé par email dès que votre compte sera accessible.'); location.href='../Home.aspx';", true);
        }
        private int RandomNumber(int min, int max)
        {
            var random = new Random();
            return random.Next(min, max);
        }
    }
}
